package com.gary.vueblog.exception;

import com.gary.vueblog.entity.ResultInfo;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 *  全局异常捕捉
 * @author pengrui
 * @date 2020/12/8 - 15:07
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public ResultInfo handler(ShiroException e) {
        System.out.println("shiro异常-----");
        e.printStackTrace();
        return ResultInfo.res(401, e.getMessage(), null);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public ResultInfo handler(RuntimeException e) {
        System.out.println("运行时异常-----");
        e.printStackTrace();
        return ResultInfo.res(500, e.getMessage(), null);
    }

    /**
     *  方法参数校验异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultInfo handler(MethodArgumentNotValidException e) {
        System.out.println("实体类校验异常-----");
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultInfo.res(500, objectError.getDefaultMessage(), null);
    }

    /**
     *  断言 非法参数异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResultInfo handler(IllegalArgumentException e) {
        System.out.println("断言抛出异常-----");
        e.printStackTrace();
        return ResultInfo.res(500, e.getMessage(), null);
    }
}
